// pages/confirm_order/index.js
import {
    ReDistributionMall,ReMallPay
} from "../../api/shipping.js"
import {
    getNavigationbar
} from "../../api/index.js"
Page({
    options: {

        styleIsolation: 'shared'
    },
    /**
     * 页面的初始数据
     */


    data: {
        showModal: false,
        totalNumbers: 0,
        isSlot: false,
        addressresList:[],
        modalTitle: "",
        message: "",
        confirmText: "",
        cancelText: "",
        totalNumbers:'',
        showCancelButton: false,
        scrollViewHeight: 0,
        orderList: [],
        isCoupon: false,
        note:''
    },

    /**
     * 选择优惠券回调函数方法
     */
    handleSelCoupon() {
        this.setData({
            isCoupon: true
        })
    },
      /**
     * 跳转
     * @param {*} event 
     */
    enter(event) {
        console.log('e', event)
        let obj = {
            ...event.currentTarget.dataset.value,
            agent_name: event.currentTarget.dataset.value.name,
            agent_thumb :event.currentTarget.dataset.value.logo
        }
        let objStr = encodeURIComponent(JSON.stringify(obj));
        wx.navigateTo({
            url: '/pages/brand_detail/index?obj=' + objStr,
        })
    },
    /**
     * 进货商城收获地址列表
     */
    getAddressres(item) {
        getNavigationbar({
            act: 'addressres',
            p: '1',
            rol1page: 10000,
            type: 'getlist' //getlist-获取地址列表 editor-编辑 add-新增 singleaddr-根据id获取地址
        }).then(res => {
            console.log('是是是',res)
            res.forEach(element => {
               if(element.id == this.data.params.address_id) {
                   console.log('res===>',element)
                   let datalist = []
                   datalist.push(element)
                this.setData({
                    addressresList:datalist
                })
               } 
            });
            
            console.log('进货商城收获地址列表', res)
        })
    },
    /**
     * 支付
    */
    payment() {
        console.log('支付')
        ReDistributionMall({
            act: 'oneCommitorder',
            paytype: 2,
            remove_postage: '1',
            addressid: this.data.params.address_id,
            note: this.data.note,
            sealmanid: '',
            remove_postage: '1'
        }).then(res => {
            console.log('支付', res)
            let openids = wx.getStorageSync('OPENID') 
            ReMallPay({
                act: "mini_wechat_commit",
                appid: 'wx11508f3ee9dd6329',
                openid:openids,
                channel: "",
                "out_trade_no":res.out_trade_no
            }).then(res => {
                console.log('微信支付', res)

                wx.requestPayment({
                    provider: "wxpay",
                    appid: "wx11508f3ee9dd6329",
                    timeStamp:res.timestamp,
                    nonceStr:res.noncestr,
                    package:res.package ,
                    partnerid:res.partnerid,
                    signType:res.sign_type, 
                    paySign:res.sign,
                    success: function (res) {
                        // 支付成功的回调
                        console.log('支付成功的回调', res)
                        wx.navigateTo({
                            url: '/pages/order_list/index',
                        })
                    },
                    fail: function (res) {
                        // 支付失败的回调
                        console.log('支付失败的回调', res)
                     
                        wx.showModal({
                            title: '111',
                            content: res.msg,
                            showCancel: false, // 是否显示取消按钮，设为false表示不显示
                            confirmText: '确定', // 确定按钮的文本
                            success(res) {
                                if (res.confirm) {
                                    wx.navigateTo({
                                        url: '/pages/order_list/index',
                                    })
                                }
                            }
                        });
                    }
                });
                
            })
            
        });
    },
    yuanToFen(yuan) {
        return Math.round(yuan * 100); // 将元转换为分，取整
    },
    handleGoodsDetail(e) {
        console.log('e',e)
        this.data.note = e.detail.value
    },
    /**
     * 一件代发-订单确认
     */
    getOneComfirmCart(item) {
        ReDistributionMall({
            act: 'oneComfirmCart',
            addressid:this.data.params.address_id,
            coupons:  '',
            remove_postage: '1'
        }).then(res => {
            
            res.forEach(element => {
                let num = element.total + element.total + element.logistics.postage
                Object.assign(element, {
                    num: num.toFixed(2)// 一件代发
                })
              });
              console.log('一件代发-订单确认', res)
            if (res.result == 101) {
                this.setData({
                    showModal: true,
                    modalTitle: "提示",
                    isSlot: false,
                    message: res.msg,
                    confirmText: "确认",
                    showCancelButton: false,
                    confirmAction: "confirmDelete" // 设置点击确定时的方法
                }, () => {
                    // 在setData的回调函数中调用confirmDelete方法
                });
            } else {
                this.setData({
                    orderList:res
                })
            }

        });
    },
    /**
     * 关闭弹窗回调函数方法
     */
    handleClose() {
        this.setData({
            isCoupon: false
        })
    },
     /**
     * 提示弹窗确认回调函数方法
     */
    handleModalChange(e) {
        const type = e.detail
        if (type == "confirm") {
            this.setData({
                showModal: false
            })
        } else {
            this.setData({
                showModal: false
            })
            // getApp().Tips({ title: "操作已取消" })
        }
    },
    /**
     * 计算页面可滚动区域的动态高度
     */
    computeScrollViewHeight() {
        let that = this
        let query = wx.createSelectorQuery().in(this)
        query.select('.header').boundingClientRect()
        query.select('.footer').boundingClientRect()
        query.exec(res => {
            console.log('1',res)
            let headerHeight = res[0].height;
            let footerHeight = res[0].height;
            let winHeight; // 窗口可使用高度
            let tabbarHeight; // 底部导航高度
            // let navTopHeight = headerHeight + tabsHeight
            wx.getSystemInfo({
                success: (res) => {
                    winHeight = res.windowHeight
                    tabbarHeight = res.windowHeight - res.safeArea.bottom // 计算底部导航总高度比变化
                }
            })
            let scrollHeight = winHeight - headerHeight - footerHeight - tabbarHeight;
            // 滚动区域高度
            that.setData({
                scrollViewHeight: scrollHeight + 60,
                tabbarHeight: tabbarHeight
            })
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (options.data) {
            let params = JSON.parse(options.data)
            this.data.params = {
                ...params
            }
            // this.data.params.address_id = params.addressId
            console.log('进', params, this.data.params)
            this.setData({
                totalNumbers:params.totalNumbers
            })
            wx.nextTick(() => {
                this.getOneComfirmCart(params);
                this.getAddressres();
            })
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.computeScrollViewHeight()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})